package com.hfzy.ihk.common.core.elasticsearch.base;

import com.hfzy.ihk.common.facade.elasticsearch.ElasticsearchTableOperation;
import com.hfzy.ihk.common.facade.elasticsearch.entity.ElasticsearchTable;
import com.hfzy.ihk.common.core.elasticsearch.ElasticsearchOperation;
import com.hfzy.ihk.common.util.string.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2018/7/18.
 *
 * @author wws
 */
public abstract class AbstractTableOperationHandler implements OperationHandler {

    private static final Logger logger = LoggerFactory.getLogger(AbstractTableOperationHandler.class);

    protected ElasticsearchTable table;

    protected ElasticsearchTableOperation tableOperation;

    public AbstractTableOperationHandler() {
    }

    /**
     * 实际的表操作
     * */

    @Override
    public boolean handle(ElasticsearchOperation elasticsearchOperation) {
        try {

            check(elasticsearchOperation);

            toHandle(elasticsearchOperation);

        } catch (Exception e) {
            handleError(elasticsearchOperation,e);
            return false;
        }

        return true;
    }

    /**
     *
     * 具体操作在此实现
     * */
    protected abstract void toHandle(ElasticsearchOperation elasticsearchOperation);

    /***
     *
     * 表操作失败的处理
     * */
    protected abstract void handleError(ElasticsearchOperation elasticsearchOperation,Exception e);

    @Override
    public ElasticsearchTable getTable() {
        if(table == null){
            throw new RuntimeException("table 未设置");
        }
        return table;
    }

    @Override
    public ElasticsearchTableOperation getTableOperation() {
        if(tableOperation == null){
            throw new RuntimeException("tableOperation 未设置");
        }
        return tableOperation;
    }

    /**
     * //TODO
     * 检查插入的操作是否与想要的一致
     * */
    public void check(ElasticsearchOperation elasticsearchOperation) {

        if(!(getTable().getTableName().equals(elasticsearchOperation.getOptTable()) && getTableOperation().getOperationName().equals(elasticsearchOperation.getOptMethod()))){

            String msg = StringUtil.format("错误，你所配置的处理器与实际table和operation不一致," +
                            "实际table:{0},实际operation:{1},预期table:{2},预期operation:{3}",
                    elasticsearchOperation.getOptTable(), elasticsearchOperation.getOptMethod(),getTable().getTableName(),getTableOperation().getOperationName());
            throw new RuntimeException(msg);
        }
    }
}
